//
//  BrainStormFromViewController.m
//  Gxj
//
//  Created by 刘伟 on 2017/8/29.
//  Copyright © 2017年 wkq. All rights reserved.
//

#import "BrainStormFromViewController.h"
#import "SDCycleScrollView.h"
#import "MyTableViewCell.h"
#import "DebateTableViewCell.h"
#import "BrainStormFromHeadView.h"
#import "GXJPrefix.pch"
#import <SDAutoLayout.h>
#import <PYSearch.h>
#import "ThanTheStormViewController.h"
#import "DebatebrainstormViewController.h"
#import "ParticularsViewController.h"//辩论详情
#import "QualitycreationdetailsNBViewController.h"//创想详情

//          **  数据接收  **    //
        //创想风暴
#import "ImaginationThestormModel.h"
#import "ImaginationThestormModel_Two.h"
        //辩论风暴
#import "BrainStormModel.h"

//刷新
#import "ShouYeRefreshHeader.h"
#import <MJRefresh.h>

@interface BrainStormFromViewController ()<UITableViewDataSource,UITableViewDelegate,SDCycleScrollViewDelegate,PYSearchViewControllerDataSource>
{
    BrainStormFromHeadView *_headView;
    //接收数据数组创建           创想风暴
    NSMutableArray * _imaginationThestormArr;
    //modle对象创建            创想风暴
    ImaginationThestormModel * _imaginationModel;
    //辩论风暴
    
    NSMutableArray * _debateThestormArr;

    NSMutableArray *_mutableArray;
    
}
/*  表格   */
@property(nonatomic, strong) UITableView * tableView;//创建表格对象
/*  搜索条   */

@property(nonatomic, strong) UIScrollView * demoContainerView;//滚动视图
@property(nonatomic, strong) UIView * viewBack;
@property(nonatomic, strong) PYSearchViewController *searchViewController;//搜索

//导航条上拉隐藏下拉显示
@property (nonatomic, assign) CGFloat borderNum;

@end

@implementation BrainStormFromViewController
- (void)viewWillAppear:(BOOL)animated {
    self.navigationController.navigationBar.hidden = YES;
    [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
    //去掉导航栏底部的黑线
    self.navigationController.navigationBar.shadowImage = [UIImage new];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:nil];
    self.navigationController.navigationBar.hidden = NO;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    //脑暴
    [self setTableView];
    //接收数据
    //**    脑暴  /**创想风暴
    [self setChuangxiangFengbaoHomeUp];
    //**    脑暴  /**创想风暴
    [self setBianlunFengbaoHomeUp];
    //刷新数据
    [self setLoadNewData];
    
}
- (void)setLoadNewData
{
    self.tableView.mj_header = [ShouYeRefreshHeader headerWithRefreshingBlock:^{
        //Call this Block When enter the refresh status automatically
    }];
    
    // Set the callback（Once you enter the refresh status，then call the action of target，that is call [self loadNewData]）
    self.tableView.mj_header = [ShouYeRefreshHeader headerWithRefreshingTarget:self refreshingAction:@selector(setChuangxiangFengbaoHomeUp)];
    
    // Enter the refresh status immediately
    [self.tableView.mj_header beginRefreshing];
}
//接收数据
//**    脑暴  /**创想风暴
- (void)setChuangxiangFengbaoHomeUp
{
    NSString *userid = [KQUserDefaults readUserDataWithKey:@"userid"];
    
    NSDictionary *dicc = @{@"userid":userid,
                           @"type":@"1",
                           @"page":@"1",
                           @"index":@"2",
                           @"quality":@""
                           };
    
    [KQNetWork postWithURLString:[NSString stringWithFormat:@"%@/api/think/index",MAIN_URL] parameters:dicc success:^(NSDictionary *dic) {
        
        _imaginationModel = [[ImaginationThestormModel alloc] initWithDictionary:dic];
        
        _imaginationThestormArr = [NSMutableArray array];
        for (ImaginationThestormModel_Two * model in _imaginationModel.list) {
            [_imaginationThestormArr addObject:model];
        }
        
        [self.tableView reloadData];
        [self.tableView.mj_header endRefreshing];
        
        
    }
                         failure:^(NSError *error)
     {
         NSLog(@"请求错误");
     }];
}
//**    脑暴  /**辩论风暴
- (void)setBianlunFengbaoHomeUp
{
    NSString *userid = [KQUserDefaults readUserDataWithKey:@"userid"];
    
    NSDictionary *dicc = @{@"userid":userid,
                           @"type":@"2",
                           @"page":@"1",
                           @"index":@"2",
                           @"quality":@""
                           };
    [KQNetWork postWithURLString:[NSString stringWithFormat:@"%@/api/think/index",MAIN_URL] parameters:dicc success:^(NSDictionary *dic) {
        
        //_debateThestormModel = [[DebateThestormModel alloc] initWithDictionary:dic];
        
        
        _debateThestormArr = [NSMutableArray array];
        _mutableArray = [NSMutableArray array];
        BrainStormModel * model= [[BrainStormModel alloc] init];
        [model setValuesForKeysWithDictionary:dic];
        
        
        
        for (NSDictionary * dicList in model.list)
        {
            BianlunData_list * modelList =[[BianlunData_list alloc] init];
            [modelList setValuesForKeysWithDictionary:dicList];
            BianlunData_list_comment *modelListComment = [[BianlunData_list_comment alloc] init];
            [modelListComment setValuesForKeysWithDictionary:modelList.comment];
            [_debateThestormArr addObject:modelList];
            [_mutableArray addObject:modelListComment];
            [self.tableView reloadData];
            
        }
        
        
        [self.tableView.mj_header endRefreshing];
        
        
    }
                         failure:^(NSError *error)
     {
         NSLog(@"请求错误");
     }];
}


#pragma mark - 脑暴
- (void)setTableView{

    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;// 去掉所有cell的分割线
    //创建滚动视图
    _demoContainerView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, kHeightScale(157))];
    //滚动视图的位置
    _demoContainerView.contentSize = CGSizeMake(UIScreenWidth,kHeightScale(157));
    _viewBack=[[UIView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, kHeightScale(157))];
    _viewBack.backgroundColor=[UIColor whiteColor];
    
    _headView = [[BrainStormFromHeadView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, kHeightScale(160))];
    [_demoContainerView addSubview:_headView];
    _borderNum = 15.f;
    self.tableView.tableHeaderView = _viewBack;
    self.tableView.backgroundColor = [UIColor colorWithRed:242.0/255.0 green:242.0/255.0 blue:242.0/255.0 alpha:1];
    [self.viewBack addSubview:self.demoContainerView];
    
    //Blick传值
    __block typeof(self) weakSelf = self;
    _headView.searchPushBlock = ^(PYSearchViewController *vc) {
        [weakSelf.navigationController pushViewController:vc animated:YES];
    };
    
    _headView.searchPopBlock = ^(PYSearchViewController *vc) {
        [weakSelf.navigationController popViewControllerAnimated:YES];
    };
    
    _headView.newspushBlock = ^(BOOL isSelect) {
        [weakSelf.navigationController pushViewController:[NewsFromViewController new] animated:YES];
    };
    
//    view.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    [self.view addSubview:_tableView];
}
//返回每个分区下的单元格个数，必须实现
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    NSInteger inter;
    if (section==0) {
        inter = _imaginationThestormArr.count;//第一组有1行
    } else {
        inter = _debateThestormArr.count;//第二组不定 （按数据展示）
    }
    return inter;
}
//返回每个分区的个数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}


- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    //第一个分区内容 Cell
    if (indexPath.section == 0) {
        static NSString * str1 =@"cell";
        MyTableViewCell * cell=[tableView dequeueReusableCellWithIdentifier:str1];
        if (!cell) {
            cell=[[MyTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:str1];
        }
        cell.selectionStyle=UITableViewStylePlain;
        cell.model=_imaginationThestormArr[indexPath.row];
        if (indexPath.row == _imaginationThestormArr.count-1) {
            cell.lineBack.hidden = YES;
        } else {
            cell.lineBack.hidden = NO;
        }
        return cell;
    }
    //第二个分区内容 Cell
    else{
        static NSString * str =@"biao";
        DebateTableViewCell*cellT=[tableView dequeueReusableCellWithIdentifier:str];
        if (!cellT) {
            cellT=[[DebateTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:str];
        }
        cellT.selectionStyle = UITableViewStylePlain;
        cellT.model = _debateThestormArr[indexPath.row];
        cellT.list_comment = _mutableArray[indexPath.row];
        if (indexPath.row == _debateThestormArr.count-1) {
            cellT.lineBack.hidden = YES;
        } else {
            cellT.lineBack.hidden = NO;
        }
        return cellT;
        }
    return nil;
}

//点击
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0)
    {
//        [tableView deselectRowAtIndexPath:indexPath animated:NO];
//        MyTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
//        cell.selected=YES;
        [self.navigationController pushViewController:[QualitycreationdetailsNBViewController new] animated:YES];
    }
    else if (indexPath.section == 1)
    {
//        [tableView deselectRowAtIndexPath:indexPath animated:NO];
//        DebateTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
//        cell.selected=YES;
        [self.navigationController pushViewController:[ParticularsViewController new] animated:YES];
    }
}


//设置页眉的高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return kHeightScale(36);
}
//设置页脚
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section == 0)
    {
        return 0;
    }
    else
    {
        return 0;
    }
    
}

//设置对应位置的cell的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    CGFloat ffloat;
    if (indexPath.section == 0) {
        ffloat = kHeightScale(293);
    }else{
        BianlunData_list_comment * _model_list_comment = _mutableArray[indexPath.row];
        
        if (![_model_list_comment.head_img isEqualToString:@""]) {
            ffloat = kHeightScale(199.5);
        }else
        {
            ffloat = kHeightScale(172.5);
        }
    };
    return ffloat;
}

//自适应Cell高度--加Model
//-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//    DuanziData *model = _dataArr[indexPath.row];
//    return [tableView cellHeightForIndexPath:indexPath model:model keyPath:@"model" cellClass:[DuanziTableViewCell class] contentViewWidth:[UIScreen mainScreen].bounds.size.width];
//}

//自定义标题
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UIView *view = [UIView new];
    
    NSArray *arr = @[@"创想风暴",@"辩论风暴"];
    
    
    UIImageView *leftImg = [[UIImageView alloc] init];
    leftImg.image = [UIImage imageNamed:@"fanhui"];
    // 填充
    leftImg.contentMode = UIViewContentModeScaleAspectFit;
    [view addSubview:leftImg];
    
    UILabel * lab2 = [[UILabel alloc]init];
    lab2.textAlignment = 0;
    lab2.font = [UIFont boldSystemFontOfSize:kWidthScale(15)];
    lab2.textColor = [UIColor colorWithHexString:@"#333333"];
    lab2.text = arr[section];
    [view addSubview:lab2];
    

    lab2.sd_layout
    .centerYEqualToView(view)
    .leftSpaceToView(view, kWidthScale(15))
    .widthIs(kWidthScale(100))
    .autoHeightRatio(0);
        
    leftImg.sd_layout
    .centerYEqualToView(view)
    .rightSpaceToView(view,kWidthScale(15))
    .widthIs(kWidthScale(15))
    .heightIs(kHeightScale(15));
    
    view.backgroundColor = [UIColor colorWithRed:242.0/255.0 green:242.0/255.0 blue:242.0/255.0 alpha:1];
    
    //创建一个手势进行点击，这里可以换成button
    
    UIButton * but = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, UIScreenWidth, kHeightScale(38))];
    but.tag = 300+section;
    but.backgroundColor = [UIColor clearColor];
    [but addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:but];
    
    return view;
}


-(void)click:(UIButton *)sender
{
    UIButton *btn = (UIButton *)sender;
    
    switch (btn.tag) {
        case 300:
            [self.navigationController pushViewController:[ThanTheStormViewController new] animated:YES];
            break;
            
        case 301:
            [self.navigationController pushViewController:[DebatebrainstormViewController new] animated:YES];
            break;
            
            
        default:
            break;
    }
    
    //有动画的刷新
//        [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:[str integerValue]]withRowAnimation:UITableViewRowAnimationFade];
}



-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    static float lastOffY  = 0;
    float curOffY = scrollView.contentOffset.y;
    
    if (scrollView.frame.size.height >= scrollView.contentSize.height ||     //内容高度低于scrollView高度，不隐藏
        fabs(curOffY)  +UIScreenWidth> scrollView.contentSize.height || //拉至最底部时，不做处理
        curOffY < 0                                                          //拉至最顶部时，不做处理
        )
    {
        return;
    }
    
    if (curOffY - _headView.navigationView.origin.y > 10)
    {
        //向上
        lastOffY = curOffY;
        [self.view addSubview:_headView.navigationView];
        _headView.navImage.image = [UIImage imageNamed:@"tbg"];
        _headView.navigationView.alpha = (curOffY -_borderNum )/_borderNum;
    }
    else if(UIScreenHeight -curOffY > UIScreenHeight - 90)
    {
        //向下
        lastOffY = curOffY;
        [_headView addSubview:_headView.navigationView];
        _headView.navImage.image = [UIImage imageNamed:@""];
        _headView.navigationView.alpha = (_borderNum -curOffY )/_borderNum;
    }
}

- (void)showTabBar
{
    if (self.tabBarController.tabBar.hidden == NO)
    {
        return;
    }
    
    UIView *contentView;
    if ([[self.tabBarController.view.subviews objectAtIndex:0] isKindOfClass:[UITabBar class]])
        contentView = [self.tabBarController.view.subviews objectAtIndex:1];
    else
        contentView = [self.tabBarController.view.subviews objectAtIndex:0];
    
    contentView.frame = CGRectMake(contentView.bounds.origin.x,
                                   contentView.bounds.origin.y,
                                   contentView.bounds.size.width,
                                   contentView.bounds.size.height - self.tabBarController.tabBar.frame.size.height);
    
    CATransition *animation = [CATransition animation];
    animation.duration = 0.4f;
    animation.type = kCATransitionMoveIn;
    animation.subtype = kCATransitionFromTop;
    self.tabBarController.tabBar.hidden = NO;
    [self.tabBarController.tabBar.layer addAnimation:animation forKey:@"animation2"];
    
    CATransition *animation1 = [CATransition animation];
    animation1.duration = 0.4f;
    animation1.type = kCATransitionMoveIn;
    animation1.subtype = kCATransitionFromBottom;
    self.navigationController.navigationBarHidden = NO;
    [self.navigationController.navigationBar.layer addAnimation:animation1 forKey:@"animation3"];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"bg"]forBarMetrics:UIBarMetricsDefault];
}

- (void)hideTabBar
{
    if (self.tabBarController.tabBar.hidden == YES)
    {
        return;
    }
    UIView *contentView;
    if ( [[self.tabBarController.view.subviews objectAtIndex:0] isKindOfClass:[UITabBar class]] )
        contentView = [self.tabBarController.view.subviews objectAtIndex:1];
    else
        contentView = [self.tabBarController.view.subviews objectAtIndex:0];
    contentView.frame = CGRectMake(contentView.bounds.origin.x,
                                   contentView.bounds.origin.y,
                                   contentView.bounds.size.width,
                                   contentView.bounds.size.height + self.tabBarController.tabBar.frame.size.height);
    
    
    CATransition *animation1 = [CATransition animation];
    animation1.timingFunction=UIViewAnimationCurveEaseInOut;
    animation1.duration = 0.4f;
    //    animation1.delegate = self;
    animation1.type = kCATransitionReveal;
    animation1.subtype = kCATransitionFromTop;
    [self.navigationController.navigationBar setBackgroundImage:[UIImage new]forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar.layer addAnimation:animation1 forKey:@"animation0"];
    
    //定义个转场动画
    CATransition *animation = [CATransition animation];
    //转场动画持续时间
    animation.duration = 0.4f;
    //计时函数，从头到尾的流畅度？？？
    animation.timingFunction=UIViewAnimationCurveEaseInOut;
    //转场动画类型
    animation.type = kCATransitionReveal;
    //转场动画子类型
    animation.subtype = kCATransitionFromBottom;
    //动画时你需要的实现
    self.tabBarController.tabBar.hidden = YES;
    //添加动画 （转场动画是添加在层上的动画）
    [self.tabBarController.tabBar.layer addAnimation:animation forKey:@"animation1"];
}
#pragma mark - 设置导航
- (void)initNavigation{
    self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];
    self.navigationItem.title = self.tabBarItem.title;
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor blackColor]}];
    self.view.backgroundColor = [UIColor whiteColor];
}

- (UITableView *)tableView
{
    if (!_tableView)
    {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, -20, UIScreenWidth, UIScreenHeight+20) style:UITableViewStylePlain];
        _tableView.delegate=self;
        _tableView.dataSource=self;
    }
    return _tableView;
}

#pragma mark  -数据接收

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
